package top.zhenganwen.securitydemo.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletWebRequest;
import top.zhenganwen.securitydemo.dto.User;
import top.zhenganwen.securitydemo.dto.UserQueryConditionDto;
import top.zhenganwen.securitydemo.service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * @author zhenganwen
 * @date 2019/8/18
 * @desc UserController
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(getClass());;

    @Autowired
    private UserService userService;

    @Autowired
    private ProviderSignInUtils providerSignInUtils;

    @PostMapping("/register")
    public String register(String username, String password, String type, HttpServletRequest request) {
        if ("register".equalsIgnoreCase(type)) {
            logger.info("新增用户并关联QQ登录, 用户名:{}", username);
            userService.insertUser();
        } else if ("binding".equalsIgnoreCase(type)) {
            logger.info("给用户关联QQ登录, 用户名:{}", username);
        }
        providerSignInUtils.doPostSignUp(username, new ServletWebRequest(request));
        return "success";
    }

    @GetMapping("/info1")
    public Object info1() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @GetMapping("/info2")
    public Object info2(Authentication authentication) {
        return authentication.getPrincipal();
    }

    @GetMapping("/info3")
    public Object info3(@AuthenticationPrincipal UserDetails currentUser) {
        return currentUser;
    }

    @GetMapping
    @JsonView(User.UserBasicView.class)
    @ApiOperation("用户查询服务")
    public List<User> query(String userName, UserQueryConditionDto userQueryConditionDto, Pageable pageable) {
        System.out.println(userName);
        System.out.println(ReflectionToStringBuilder.toString(userQueryConditionDto, ToStringStyle.MULTI_LINE_STYLE));
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getSort());
//        List<User> users = Arrays.asList(new User(1L,"tom","123"), new User(2L,"jack","456"), new User(3L,"alice","789"));
//        return users;
        return null;
    }

    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailsView.class)
    public User getInfo(@PathVariable("id") Long id) {
        System.out.println("[UserController # getInfo]query user by id");
        throw new RuntimeException("id not exist");
//        return new User();
    }

    @PostMapping
    public void createUser(@Valid @RequestBody User user) {
        System.out.println(user);
    }

    @PutMapping("/{id:\\d+}")
    public void update(@PathVariable Long id, @Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) {
            errors.getAllErrors().stream().forEach(error -> {
                FieldError fieldError = (FieldError) error;
                System.out.println(fieldError.getField() + " " + fieldError.getDefaultMessage());
            });
        }
        System.out.println(user);
    }


}
